package com.sense.kukoo.biz_share.view

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.share.Sharer
import com.facebook.share.model.ShareLinkContent
import com.facebook.share.widget.ShareDialog
import com.sense.feel.common.utils.ToastUtils
import com.sense.kukoo.biz_share.R
import com.sense.kukoo.biz_share.databinding.BizShareActivityShareBinding
import com.sense.kukoo.biz_share.vm.ShareViewModel
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.mvvm.view.BaseMvvmActivity
import com.sense.kukoo.common.repo.bean.BookBean
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.lib_logger.LoggerManager
import com.sense.kukoo.lib_picture.config.GlideConfig
import com.sense.kukoo.lib_picture.loader.Monet


@Route(path = ARouterUrl.ROUTE_SHARE_MODULE_SHARE_ACTIVITY)
class ShareActivity : BaseMvvmActivity<ShareViewModel, BizShareActivityShareBinding>() {
    private val LINE_PACKAGE_NAME = "jp.naver.line.android"

    private val TAG: String = javaClass.simpleName

    @JvmField
    @Autowired(name = ARouterUrl.KEY_SHARE_BOOK_TITLE)
    var title: String? = null
    @JvmField
    @Autowired(name = ARouterUrl.KEY_SHARE_BOOK_TYPE)
    var type: Int = -1
    @JvmField
    @Autowired(name = ARouterUrl.KEY_SHARE_BOOK_SUB_TITLE)
    var subTitle: String? = null
    @JvmField
    @Autowired(name = ARouterUrl.KEY_SHARE_BOOK_AUTHOR)
    var author: String? = null
    @JvmField
    @Autowired(name = ARouterUrl.KEY_SHARE_BOOK_URL)
    var url: String? = null
    @JvmField
    @Autowired(name = ARouterUrl.KEY_SHARE_BOOK_IMAGE_URL)
    var imageUrl: String? = null
    var callbackManager : CallbackManager? = null
    override fun getLayoutId(): Int = R.layout.biz_share_activity_share

    override fun getViewModelClass(): Class<ShareViewModel> = ShareViewModel::class.java

    override fun responseVM(action: Int) {}

    override fun initData() {
        ARouter.getInstance().inject(this)
        //
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        //mViewModel.initData(from!!)
        //
        bindAction(mViewModel.action_back){
            finish()
        }
        bindAction(mViewModel.faceBookShare) {
            callbackManager = CallbackManager.Factory.create();
            val shareDialog = ShareDialog(this);
            shareDialog.registerCallback(callbackManager!!, object : FacebookCallback<Sharer.Result>{
                override fun onCancel() {
                    hideLoadingDialog()
                    LoggerManager.i(TAG,"onCancel")
                }

                override fun onError(error: FacebookException) {
                    hideLoadingDialog()
                    error.printStackTrace()
                    LoggerManager.i(TAG,error.message.toString())
                }

                override fun onSuccess(result: Sharer.Result) {
                    hideLoadingDialog()
                    LoggerManager.i(TAG,result.toString())
                }
            })
            if (ShareDialog.canShow(ShareLinkContent::class.java)) {
                showLoadingDialog()
                val linkContent: ShareLinkContent = ShareLinkContent.Builder()
                    .setContentUrl(Uri.parse(url))
                    .build()
                shareDialog.show(linkContent)
            }
        }
        bindAction(mViewModel.lineShare) {
            if (!isAppInstalled(this,LINE_PACKAGE_NAME)){
                val openURL = Intent(android.content.Intent.ACTION_VIEW)
                openURL.data = Uri.parse("https://line.me/R/")
                startActivity(openURL)
                return@bindAction
            }
            showLoadingDialog()
            val intent =  Intent();
            intent.action = Intent.ACTION_SEND;
            intent.putExtra(Intent.EXTRA_TEXT, url);
            intent.type = "text/plain";
            intent.setPackage(LINE_PACKAGE_NAME)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            startActivity(intent);
        }
        bindAction(mViewModel.copyShare) {
            //获取剪贴板管理器：
            val cm: ClipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
            // 创建普通字符型ClipData
            val mClipData = ClipData.newPlainText("Label", url)
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData)
            ToastUtils.showToast(getString(com.sense.kukoo.common_i18n.R.string.share_copy_success))
            finish()
        }
    }


    private fun isAppInstalled(context: Context, packageName: String): Boolean {
        var packageInfo: PackageInfo? = null
        try {
            packageInfo = context.packageManager.getPackageInfo(packageName, 0)
        } catch (e: PackageManager.NameNotFoundException) {
        }
        return packageInfo != null
    }

    override fun onResume() {
        super.onResume()
        hideLoadingDialog()
    }


    private fun convertBookType(type:Int?):String{
        return when (type) {
            BookBean.TYPE_UNKNOW -> {
                ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.explore_type_unknow)
            }
            BookBean.TYPE_AUDIOBOOK -> {
                ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.explore_type_audiobook)
            }
            BookBean.TYPE_PODCAST -> {
                ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.explore_type_podcast)
            }
            BookBean.TYPE_SHORT_AUDIO -> {
                ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.explore_type_short_audio)
            }
            else -> {""}
        }
    }

    override fun initView() {
        //
        mBinding.tvTitle.setText(title)
        mBinding.tvMusicType.setText(convertBookType(type))
        mBinding.tvShareByName.setText(author)
        Monet.get(ApplicationContext.instance())
            .load<GlideConfig>(imageUrl)
            .placeholder(com.sense.kukoo.common.R.mipmap.common_icon_default_editor_picks)
            .into(mBinding.ivMusicIcon)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LoggerManager.i(TAG,"onActivityResult $requestCode")
        callbackManager?.onActivityResult(requestCode, resultCode, data);
    }
}